package dms.presentation.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dms.model.role.Account;
import dms.model.role.Role;
import dms.util.Constant;

/**
 * Servlet Filter implementation class SystemAdministratorFilter
 */
public class SystemAdministratorFilter implements Filter {

    /**
     * Default constructor. 
     */
    public SystemAdministratorFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		Account account = null;
		HttpSession session = httpRequest.getSession(false);
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		if (session == null) {
			httpResponse.sendRedirect(Constant.LOGIN_PARH);
			return ;
		}
		account = (Account) session.getAttribute(Constant.ACCOUNT);
		if (account == null) {
			httpResponse.sendRedirect(Constant.LOGIN_PARH);
			return ;
		}
		
		if (!account.getRole().equals(Role.SYSTEM_ADMINISTRATOR)) {
			httpResponse.sendRedirect(Constant.LOGIN_PARH);
			return ;
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
